'use strict';

const { Service } = require('ee-core');
// 框架提供的数据库对象
// ee-core:v2.0.1
const Storage = require('ee-core/storage'); 
const _ = require('lodash');

/**
 * 数据存储
 * @class
 */
class StorageService extends Service {

  configDb = {
    table: 'list',
    field: ['id', 'auction_id','content', 'zc_id', 'listOrder', 'priceG', 'author', 'size', 'priceRmb', 'type', 'title','date','thumb', 'url', 'status', 'remark', 'created_at',  'updated_at']
  }
  constructor (ctx) {
    super(ctx);
    
    // demo库
    let jsondbOptions = {
      driver: 'jsondb'
    }
    this.collectDB = Storage.connection('artStoreage', jsondbOptions);

    if (!this.collectDB.db.has(this.configDb.table).value()) {
      this.collectDB.db.set(this.configDb.table, []).write();
    }
  }

   /**
   * test
   */
   async add(collect) {
    
    var configDb = this.configDb
    var newObj = {};
    for (const key of configDb.field) {
      newObj[key] = collect[key];
    }
    newObj.created_at = new Date().toLocaleDateString() + ' ' + new Date().toLocaleTimeString()
    newObj.updated_at = newObj.created_at
    const num = this.collectDB.db.get(this.configDb.table).filter({id: newObj.id}).size().value()
    if(num >0) {
      return false
    }
    const data = this.collectDB.db
        .get(this.configDb.table)
        .push(newObj)
        .write();
    return data;
  }
  async show(id) {
    let data = this.collectDB.db
      .get(this.configDb.table)
      .find({id})
      .value();
    
    if (_.isEmpty(data)) {
      data = []
    }
    
    return data;
  }
  async update(data) {
    console.log(data)
    let ret = this.collectDB.db
      .get(this.configDb.table)
      .find({id: data.id})
      .assign(data)
      .write();
    console.log(ret)
    return ret;
  }

  async list(where, limit) {
    let data = this.collectDB.db
      .get(this.configDb.table)
      .filter(where)
      .orderBy(function(item){
        return new Date(item.created_at).getTime()
      }, 'desc')
      .take(limit)
      .value();
    
    if (_.isEmpty(data)) {
      data = []
    }
    
    return data;
  }
  async count(where) {
    let data = this.collectDB.db
      .get(this.configDb.table)
      .filter(where)
      .size()
      .value();
    
    return data;
  }
  async delete(where) {
    let data = this.collectDB.db
      .get(this.configDb.table)
      .remove(where)
      .write();
    
    if (_.isEmpty(data)) {
      data = []
    }
    
    return data;
  }
}

module.exports = StorageService;
